app.component.html
中組裝這些元件.ts
→ 邏輯程式(控制資料、事件).html
→ 模板(畫面結構).scss
→ 樣式(只作用在這個元件)👉 這樣每個部分都各自獨立,方便維護。就像樂高積木一樣,網站就是一堆元件拼在一起。
我們的履歷網站可以拆成這幾個主要元件:
header
→ 網站導覽列(名字、選單、主題切換)hero
→ 首屏區塊(自我介紹 + 照片)about
→ 關於我(文字 + 更多介紹按鈕)skills
→ 技能區(清單 + 篩選)projects
→ 作品集(卡片清單)contact
→ 聯絡我(表單 + 其他聯絡方式)footer
→ 頁尾(版權訊息)在專案目錄輸入:
ng g c components/header
ng g c components/hero
ng g c components/about
ng g c components/skills
ng g c components/projects
ng g c components/contact
ng g c components/footer
這會自動產生像這樣的結構:
src/app/components/
├─ header/
│ ├─ header.component.ts
│ ├─ header.component.html
│ ├─ header.component.scss
│ └─ header.component.spec.ts
├─ hero/
├─ about/
...
header.component.html
→ 放 <header>
裡的 HTMLhero.component.html
→ 放 Hero 區塊about.component.html
→ 放 About 區塊範例:header.component.html
<header class="site-header">
<div class="container">
<a class="brand" href="#home">Chiayu</a>
<nav class="site-nav" aria-label="主選單">
<ul>
<li><a href="#about">關於我</a></li>
<li><a href="#skills">技能</a></li>
<li><a href="#projects">作品</a></li>
<li><a href="#contact">聯絡</a></li>
</ul>
</nav>
<button id="theme-toggle" type="button" aria-pressed="false">切換主題</button>
</div>
</header>
app.component.html
組裝元件CLI 幫我們自動註冊了元件,所以可以直接用標籤呼叫:
<app-header></app-header>
<app-hero></app-hero>
<app-about></app-about>
<app-skills></app-skills>
<app-projects></app-projects>
<app-contact></app-contact>
<app-footer></app-footer>
這樣就等於把一個大 HTML 拆成多個「小積木」。
app.component.html
現在非常乾淨,只剩下組裝用的 <app-xxx>
標籤index.html
index.html
只有 <app-root>
.component.html
app.component.html
使用元件
.scss
只作用在該元件styles.scss
@Component({ selector: 'app-header' })
→ <app-header></app-header>
明天我們要開始學 Angular 的資料綁定 (Data Binding):
{{ }}
)在模板中顯示變數